package com.silent.ssjr.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

public class SecurityConfigration extends WebSecurityConfigurerAdapter {

//    保证刷新token时刷新成功
    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder.userDetailsService(userDetailsService());
    }

    @Bean
    @Override
    protected UserDetailsService userDetailsService() {
//        添加用户到内存
        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
        inMemoryUserDetailsManager.createUser(User.withUsername("user1").password("user1").authorities("User").build());
        inMemoryUserDetailsManager.createUser(User.withUsername("user2").password("user2").authorities("User").build());
        return inMemoryUserDetailsManager;

//        实际开发从数据库获取数据
        /*return new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
                boolean isUserExist = false;
                if (isUserExist){
//                    创建spring security安全用户和对应的权限（从数据看中查询）
                    User user = new User("username","password", AuthorityUtils.createAuthorityList("admin","manager"));
                    return user;
                }else {
                    throw new UsernameNotFoundException("用户" + s + "不存在！");
                }
            }
        };*/

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        @formatter:off
        http.requestMatchers().anyRequest().and().authorizeRequests().antMatchers("/oauth/**").permitAll();
//        @formatter:on
    }

}
